import { useEffect, useState } from 'react';

// 1. load 事件
function LoadDemo() {
  const [msg, setMsg] = useState('');
  useEffect(() => {
    function onLoad() {
      setMsg('页面已加载完毕');
    }
    window.addEventListener('load', onLoad);
    return () => window.removeEventListener('load', onLoad);
  }, []);
  return <div>load: {msg}</div>;
}

// 2. scroll 事件
function ScrollDemo() {
  const [y, setY] = useState(window.scrollY);
  useEffect(() => {
    function onScroll() {
      setY(window.scrollY);
    }
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div>scrollY: {y}</div>;
}

// 3. beforeunload 事件
function BeforeUnloadDemo() {
  useEffect(() => {
    function onBeforeUnload(e) {
      e.preventDefault();
      e.returnValue = '';
    }
    window.addEventListener('beforeunload', onBeforeUnload);
    return () => window.removeEventListener('beforeunload', onBeforeUnload);
  }, []);
  return <div>尝试关闭页面会有提示</div>;
}

// 4. hashchange 事件
function HashChangeDemo() {
  const [hash, setHash] = useState(window.location.hash);
  useEffect(() => {
    function onHashChange() {
      setHash(window.location.hash);
    }
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);
  return <div>当前 hash: {hash}</div>;
}

// 5. online/offline 事件
function OnlineDemo() {
  const [online, setOnline] = useState(navigator.onLine);
  useEffect(() => {
    function updateStatus() {
      setOnline(navigator.onLine);
    }
    window.addEventListener('online', updateStatus);
    window.addEventListener('offline', updateStatus);
    return () => {
      window.removeEventListener('online', updateStatus);
      window.removeEventListener('offline', updateStatus);
    };
  }, []);
  return <div>网络状态：{online ? '在线' : '离线'}</div>;
}

// 6. keydown 事件
function KeydownDemo() {
  const [key, setKey] = useState('');
  useEffect(() => {
    function onKeydown(e) {
      setKey(e.key);
    }
    window.addEventListener('keydown', onKeydown);
    return () => window.removeEventListener('keydown', onKeydown);
  }, []);
  return <div>最近按下的键：{key}</div>;
}

// 7. visibilitychange 事件
function VisibilityDemo() {
  const [visible, setVisible] = useState(document.visibilityState);
  useEffect(() => {
    function onVisibilityChange() {
      setVisible(document.visibilityState);
    }
    document.addEventListener('visibilitychange', onVisibilityChange);
    return () => document.removeEventListener('visibilitychange', onVisibilityChange);
  }, []);
  return <div>页面可见性：{visible}</div>;
}

export { LoadDemo, ScrollDemo, BeforeUnloadDemo, HashChangeDemo, OnlineDemo, KeydownDemo, VisibilityDemo };
